const TASK_ADDED = "added";
const TASK_CHANGED = "changed";
const TASK_DELETED = "deleted";

let nextId = 3;
export const initialTasks = [
  { id: 0, text: "Visit Kafka Museum", done: true },
  { id: 1, text: "Watch a puppet show", done: false },
  { id: 2, text: "Lennon Wall pic", done: false },
];

export function addedAction(text) {
  return {
    type: TASK_ADDED,
    id: nextId++,
    text: text,
  };
}

export function changedAction(task) {
  return {
    type: TASK_CHANGED,
    task: task,
  };
}

export function deletedAction(taskId) {
  return {
    type: TASK_DELETED,
    id: taskId,
  };
}

export function tasksReducer(tasks = initialTasks, action) {
  switch (action.type) {
    case TASK_ADDED: {
      return [
        ...tasks,
        {
          id: action.id,
          text: action.text,
          done: false,
        },
      ];
    }
    case TASK_CHANGED: {
      return tasks.map((t) => {
        if (t.id === action.task.id) {
          return action.task;
        } else {
          return t;
        }
      });
    }
    case TASK_DELETED: {
      return tasks.filter((t) => t.id !== action.id);
    }
    default: {
      throw Error("Unknown action: " + action.type);
    }
  }
}
